package org.lex.reflect.browsing.view.browser;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;

import org.lex.reflect.browsing.util.IconCache;
import org.lex.swing.ActionBuilder;


public class MethodsPane extends JPanel {
	private JScrollPane scrollPane;
	private JToolBar toolBar;
	private JToggleButton sortToggleButton;
	private JToggleButton showAllToggleButton;
	private JList list;
	private MethodListModel model = null;

	public MethodsPane() {
		super(new BorderLayout());
		this.add(getToolBar(), BorderLayout.NORTH);
		this.add(getScrollPane(), BorderLayout.CENTER);
	}

	public void setClass(Class<?> clazz) {
		this.getModel().setClass(clazz);
	}

	private JToolBar getToolBar() {
		if (toolBar == null) {
			toolBar = new JToolBar();
			toolBar.add(getShowAllToggleButton());
			toolBar.add(getSortToggleButton());
		}
		return toolBar;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null)
			scrollPane = new JScrollPane(this.getList());
		return scrollPane;
	}

	private JList getList() {
		if (list == null)
			list = new JList(this.getModel());
		return list;
	}

	private MethodListModel getModel() {
		if (null == model)
			model = new MethodListModel();
		return model;
	}

	private JToggleButton getShowAllToggleButton() {
		if (showAllToggleButton == null)
			showAllToggleButton = new JToggleButton(new ShowAllMembersAction());
		return showAllToggleButton;
	}

	private JToggleButton getSortToggleButton() {
		if (sortToggleButton == null)
			sortToggleButton = new JToggleButton(new SortAction());
		return sortToggleButton;
	}

	class ShowAllMembersAction extends ActionBuilder {
		ShowAllMembersAction() {
			this.setSelected(false);
			this.setTooltip("Show All Inherited Members");
			this.setIcon(IconCache.getIcon(IconCache.SHOW_ALL));
		}

		public void actionPerformed(ActionEvent e) {
			boolean selected = this.isSelected();
			getModel().setShowInheritedMembers(selected);
			getSortToggleButton().setEnabled(selected);
		}
	}

	class SortAction extends ActionBuilder {
		SortAction() {
			this.setSelected(false);
			this.setTooltip("Sort Methods by the Defining Type");
			this.setIcon(IconCache.getIcon(IconCache.SORT));
			this.setEnabled(false);
		}

		public void actionPerformed(ActionEvent e) {
			getModel().setSortByDefiningType(this.isSelected());
		}
	}
}
